package com.app.mp3player.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.app.mp3player.model.Mp3Info;
import com.app.utils.AppConstant;
import com.app.utils.HttpDownloader;

public class DownLoadService extends Service {
	private static final String TAG = "DownLoadService";
	
	public DownLoadService() {
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		//接收MP3 info
		Mp3Info mp3Info = (Mp3Info)intent.getSerializableExtra("mp3Info");
		Log.i(TAG, "onStartCommand---------->"+mp3Info.toString());
		
		DownLoadThread loadThread = new DownLoadThread(mp3Info);
		loadThread.start();
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	class DownLoadThread extends Thread{
		private Mp3Info info;
		
		public DownLoadThread(Mp3Info info) {
			this.info = info;
		}

		@Override
		public void run() {
			
			String returnStr = "";
			HttpDownloader downloader = new HttpDownloader();
			int mp3State = 1;
			int lrcState = 1;
			try {
				String mp3Path = URLEncoder.encode(info.getMp3Name()+".mp3", "utf-8");
				String lrcPath = URLEncoder.encode(info.getLrcName(), "utf-8");
				
				mp3State = downloader.downFile(AppConstant.URL.BASE_URL+mp3Path, "mp3",mp3Path);
				lrcState = downloader.downFile(AppConstant.URL.BASE_URL+lrcPath, "mp3",lrcPath);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			 
			if(mp3State ==0 && lrcState == 0){
				returnStr = "下载成功";
			}else if(mp3State == 1){
				returnStr = "已经存在";
			}else if(mp3State == -1){
				returnStr = "下载失败";
			}
			Log.i(TAG, returnStr);
		}
		
	}
}
